package com.reesechou.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.simple.JSONObject;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 小星打屁屁 on 2015/3/29.
 * contact me ==>243709758@qq.com
 */
public class KindEditorUploadServlet extends HttpServlet {
    public KindEditorUploadServlet(){
        super();
    }
    public void  doGet(HttpServletRequest request ,HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
         request.setCharacterEncoding("UTF-8");
         response.setCharacterEncoding("UTF-8");
//        在这里  kindEditor 会发送一个 get 请求，连接请求类似于：    kindEditorUpload?dir=image
        String dirName = request.getParameter("dir");
        if(dirName==null|| !StringUtils.hasText(dirName)){
            dirName = "image" ;
        }
//        设置上传文件在硬盘中的保存位置
        String savePath = request.getServletContext().getRealPath(this.getServletInfo())+"/attact/"+dirName+'/';

//		这里获取在这个 web 应用中的位置，因为直接在磁盘中的路径来获取的话是被系统保护的，不可以以类似 c:\ddd\ddd.jpg 的方式来直接获取资源
        String saveUrl = request.getContextPath()+"/attact/"+dirName +'/' ;

        System.out.println("savePath = "+savePath);
        System.out.println("saveUrl = "+saveUrl);

        long maxSize = 10240;

        //		这里设置返回页面的类型 contentType
        response.setContentType("text/html; charset=utf-8");

        PrintWriter out = response.getWriter() ;

        if(!ServletFileUpload.isMultipartContent(request)){
        //首先要判断客户端<form>标记的enctype属性是否是“multipart/form-data"
            out.println(getError("请选择文件。"));
            return;
        }
        //检查目录是否存在，若不存在则创建
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory() ){
            uploadDir.mkdirs();
        }
        //检查目录写权限
        if(!uploadDir.canWrite()){
            out.println(getError("上传目录没有写权限。"));
            return;
        }
        Map extMap = new HashMap();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> fileItemList = new ArrayList<FileItem>();
        try {
            fileItemList = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator<FileItem> iterator = fileItemList.iterator();
        if(iterator.hasNext()){
            FileItem fileItem = iterator.next();
            String fileName = fileItem.getName();
// 就是判断一个参数域是普通的表单输入域，还是文件上传域，
// 如果该方法返回真的话，则是前者，如果为假，则是后者。是后者的情况下，就要对相应的域做相应的文件上传处理。
            if(!fileItem.isFormField()){
                //说明此份fileItem为文件
                if(fileItem.getSize()>maxSize){
                    out.println(getError("文件大小超出限制！"));
                    return;
                }
                //检查文件后缀名
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//				if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
//					out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
//					return;
//				}
                ////给上传的文件内容设定一个新的名字
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File finalFile = new File(savePath,newFileName);
                try {
                    fileItem.write(finalFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                out.println(obj.toJSONString());

            }
        }
        out.flush();
        out.close();

    }
    //以 JSON 的形式返回给 KindEditor 插件，以供其显示
    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toJSONString();
    }

}
